<?php

namespace app\index\controller;

use app\BaseController;
use app\common\model\Api;
use app\common\service\Str;
use app\admin\model\user\User as UserModel;
use think\facade\Db;
use think\facade\Log;
use think\facade\Session;
use think\facade\Cache;

class Wxh5 extends BaseController
{
    public function wxauth()
    {
        $user_token = $this->request->param('user_token', '');
        $openid     = $this->request->param('openid', '');
        $host       = $this->request->host();
        $redrictUri = $this->request->param('redrictUri', '');
        $authDomain = 'http://' . $host . '/index/index/auth_login';

        if ($userToken = $user_token) {
            $sessionUserToken = Session::get("user_token");
            if ($sessionUserToken != $userToken) {//重新拉取授权
                $starwalkUrl = "{$authDomain}?redrictUri={$redrictUri}";
                header("Location:" . $starwalkUrl);
            }
        } elseif ($openId = $openid) {
            $userInfo = Session::get("WxUserInfo");
            if (empty($userInfo) || $userInfo['openid'] != $openId) {//重新拉取授权
                $starwalkUrl = "{$authDomain}?redrictUri={$redrictUri}";
                header("Location:" . $starwalkUrl);
            }
        } else {
            $starwalkUrl = "{$authDomain}?redrictUri={$redrictUri}";
            header("Location:" . $starwalkUrl);
        }
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:*');
        header('Access-Control-Allow-Headers:*');
    }

    /**
     * @Author: Bryant
     * @Date: 2023-06-15 10:20:18
     * @method post
     * @title 获取用户信息
     */
    public function auth_login()
    {
        try {
            $wxuinfo = Session::get("WxUserInfo");

            if (!$wxuinfo) {
                $wxuinfo = $this->getInformation();
                if (!$wxuinfo) {
                    throw new \Exception('获取用户信息失败');
                }
            }
            Log::info('wxuinfo' . json_encode($wxuinfo));
            //判断是否已注册
            $user_info = Db::name('user')
                ->where("gzh_openid", $wxuinfo['openid'])
                ->find();
            if (!$user_info) {//未注册直接注册
                $starwalkUrl = '/h5/#/pages/login/bind-mobile/bind-mobile?openid=' . $wxuinfo['openid'] . '&avatar=' . $wxuinfo['headimgurl'];
                $host        = 'http://weixiu.mcruanjian.cn';

                header("Location:" . $host . $starwalkUrl);
                return;

            } else {//通过公众号授权拉取到的openid在系统中已经注册过账号
                $user = UserModel::where(['id' => $user_info['id']])->find();
            }

            //获取登录需要返回的信息
            $jsonList = self::get_login_info($user);
        } catch (\Exception $e) {
            return $e->getMessage();
        }

        Session::set('user_token', $jsonList['user_token']);
        $starwalkUrl = '/h5/?user_token=' . $jsonList['user_token'];
        $host        = 'http://weixiu.mcruanjian.cn';

        header("Location:" . $host . $starwalkUrl);
        return;
    }

    /**
     * @Author: Bryant
     * @Date: 2023-06-15 10:20:25
     * @method post
     * @title 获取登录信息
     */
    public static function get_login_info($user)
    {
        // 请求接口的token
        $exp_time1    = 2592000; //token过期时间,这里设置2个小时
        $scopes1      = 'role_access'; //token标识，请求接口的token
        $access_token = Api::createToken($user, $exp_time1, $scopes1);
        $uuid         = Str::uuid();
        Cache::tag('user')->set('user_token_' . $uuid, $access_token);
        return [
            'user_token'    => $uuid,
            'id'            => $user['id'],
            'user_nickname' => $user['user_nickname'],
            'avatar'        => $user['avatar'],
            'birthday'      => $user['birthday'] ? date('Y-m-d', $user['birthday']) : '',
            'phone'         => preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $user['mobile']),
            'mobile'        => $user['mobile'],
        ];
    }
    /** 
     * @Author: Bryant  
     * @Date: 2023-08-31 17:05:51 
     * @method post 
     * @title 判断是否是微信环境 
     */
    public static function is_weixin()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        }
        return false;
    }

//    http://xiangcunrc.magic-house.cn/index/Wechat_Login/getInformation.html

    /**
     * @Author: Bryant
     * @Date: 2023-06-15 10:20:39
     * @method post
     * @title 获取用户信息
     */
    public function getInformation()
    {
        /*https://www.xcrck.com/index/Wechat_Login/getInformation.html?url=&id=12175&type=1#/?id=12175*/
        $is_wx = self::is_weixin();
        if ($is_wx) {
            $request    = $this->request;
            $redrictUri = $request->param('redrictUri', '');
            $code       = $request->param('code', '');
            if (empty($data['code'])) {//引导用户进入授权同意页
                $uri = "http://" . $_SERVER['HTTP_HOST'] . '/index/index/auth_login?' . '&redrictUri=' . $redrictUri;
                $url = self::getAuthUrl($uri, 'snsapi_userinfo');
                Header("Location:{$url}");
                exit;
            } else {
                $arr = self::getOpenid($code);
                if ($arr['access_token']) {
                    $user_info = self::getUser($arr['access_token'], $arr['openid']);
                    Session::set('WxUserInfo', $user_info);
                    return $user_info;
                } else {
                    throw new \Exception('授权失败，请重试');
                }
            }
        } else {
            $request = $this->request;
            $url     = $request->param('url', '');
            $id      = $request->param('id', '');
            $type    = $request->param('type', '');
            if ($type) {
                $url = $url . "?" . "&type=" . $type;
            }
            if ($id) {
                $url = $url . "?" . "&id=" . $id;
            }
            header("Location:" . $url);
        }

    }


    //获取授权连接,返回一个CODE
    //https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1455784140&token=&lang=zh_CN
    public static function getAuthUrl($redirect_uri, $scope = 'snsapi_userinfo', $state = 1)
    {

        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?';
        $arr = array(
            'appid'         => addons_config('WeChat.code_appid'),
            'redirect_uri'  => $redirect_uri,
            'response_type' => 'code',
            'scope'         => $scope,
            'forcePopup'    => true,
            'state'         => $state

        );
        return $url . http_build_query($arr) . '#wechat_redirect';
    }

    /**
     * @Author: Bryant
     * @Date: 2023-06-15 10:21:19
     * @method post
     * @title 获取用户信息
     */
    public function getUser($access_token, $openid)
    {
        $url  = 'https://api.weixin.qq.com/sns/userinfo?';
        $arr  = array(
            'access_token' => $access_token,
            'openid'       => $openid,
            'lang'         => 'zh_CN',
        );
        $url  .= http_build_query($arr);
        $json = $this->curl($url);
        $arr  = json_decode($json, true);
        if (!empty($arr['openid'])) {
            return $arr;
        }

        $arr['errmsg'] = $arr['errmsg'] ?? '未知';
        throw new \Exception("错误异常," . $arr['errmsg']);
    }
    /** 
     * @Author: Bryant  
     * @Date: 2023-08-31 17:12:25 
     * @method post 
     * @title 微信授权回调,获取用户access_token 和 OPENID, unionid，用getAuthUrl回调的CODE 
     */
    public static function getOpenid($code)
    {
        $url  = 'https://api.weixin.qq.com/sns/oauth2/access_token?';
        $arr  = array(
            'appid'      => addons_config('WeChat.code_appid'),
            'secret'     => addons_config('WeChat.code_appsecret'),
            'code'       => $code,
            'grant_type' => 'authorization_code',
        );
        $url  .= http_build_query($arr);
        $json = self::curl($url);
        $arr  = json_decode($json, true);
        if (!empty($arr['openid'])) {
            return $arr;
        }
        $arr['errmsg'] = $arr['errmsg'] ?? '未知';
        throw new \Exception("错误异常," . $arr['errmsg']);
    }

    //打开连接
    public static function curl($url, $post = false, $toJson = true)
    {
        if (is_array($post) && $toJson) {
            $post = json_encode($post, JSON_UNESCAPED_UNICODE);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //这个是重点。

        if ($post) {
            curl_setopt($ch, CURLOPT_POST, 1);
            // return $post;
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    /** 
     * @Author: Bryant  
     * @Date: 2023-08-31 17:11:40 
     * @method post 
     * @title 获取所有用户openid 
     */
    public function GetAllOpenid()
    {
        $url      = 'https://api.weixin.qq.com/cgi-bin/user/get?next_openid=&';
        $arr      = array(
            'access_token' => $this->getAccessToken(),
        );
        $url      .= http_build_query($arr);
        $json_obj = $this->curl($url);
        return $json_obj;
    }

    /** 
     * @Author: Bryant  
     * @Date: 2023-08-31 17:11:21 
     * @method post 
     * @title 发送模板消息 
     */
    public function replyTem($touser, $order)
    {
        $access_token = $this->getAccessToken();
        $data         = '{
           "touser":"' . $touser . '",
           "template_id":"GFlvAypCsCPprzcEwe5ULI7nZW73uG3aFPeFlsQSSvg",        
           "data":{
                "character_string2": {
                    "value":"' . $order['order_sn'] . '"
                },
                "thing4":{
                    "value":"' . $order['user_nickname'] . '"
                },
                "phone_number5": {
                    "value":"' . $order['mobile'] . '"
                },
                "thing6": {
                    "value":"' . $order['type'] . '"
                },
                "time12": {
                    "value":"' . $order['order_time'] . '"
                }
           }
       }';
        //模板消息
        $url    = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
        $result = $this->curl($url, $data, true);
        $data   = json_decode($result);
        return $data;
    }
    /** 
     * @Author: Bryant  
     * @Date: 2023-08-31 17:11:29 
     * @method post 
     * @title 获取全局access_token 
     */
    public function getAccessToken()
    {
        $access_token = Cache::get('wxcode_access_token');
        if (!$access_token) {
            $url          = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&";
            $arr          = array(
                'appid'  => addons_config('WeChat.code_appid'),
                'secret' => addons_config('WeChat.code_appsecret'),
            );
            $url          .= http_build_query($arr);
            $json         = $this->curl($url);
            $arr          = json_decode($json, true);
            $access_token = $arr['access_token'] ?? null;
            $expires_in   = $arr['expires_in'] ?? 0;
            if ($access_token && $expires_in) {
                Cache::set('wxcode_access_token', $access_token, $expires_in - 1800);
            } else {
                $arr['errmsg'] = $arr['errmsg'] ?? '未知';
                throw new \Exception("错误异常," . $arr['errmsg']);
            }
        }
        return $access_token;
    }
}